import fs from 'fs';
import path from 'path';
import inquirer from 'inquirer';
import chalk from 'chalk';

import { CheckConfigFile } from './util.js';

/**
 * 选择列表
 *
 * @param {Array} pathArray
 * @return {*} 
 */
export const ConfigCreate = () => {
    const questions = [{
        type: "list",
        name: "_index",
        message: "未找到配置文件，是否在指定位置创建？",
        choices: ['是', '否'],
        filter: val => {
            return val == '是'
        }
    }];
    return inquirer.prompt(questions);
}

const ReadFonfig = (_path) => {
    var File = fs.readFileSync(path.resolve(_path), 'utf-8');
    return new Function(File)();
}

export default async function (options) {
    let config = {};
    var _path = 'swagger.config.js';
    if (options.config) {
        _path = options.config;
    }
    // 配置文件如果存在则读取
    if (fs.existsSync(path.resolve(_path))) {
        config = ReadFonfig(_path);
        return CheckConfigFile(config, _path);
    } else {
        var HavePath = fs.existsSync(path.dirname(path.resolve(_path)));
        if (!HavePath) {
            console.log(chalk.red('指定的目录不存在'))
            return undefined;
        }
        var { _index } = await ConfigCreate();
        _index && fs.writeFileSync(path.resolve(_path), `return {
    // 用于去掉重复的 Path 字段
    "IgnoreString": ["api"],
    // swagger 文档地址
    "DocumentPath": [],
    // 接口文件输出地址
    "FolderPath":"",
    // 文档输出附加模块(头部模块)
    "InsertBefore": \`// 经过封装的请求方法地址
import request from '@/libs/request.js';\`
}`);
        return undefined;
    };

};